package com.sunda.spmsorder.util;

import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>@description:【Excel导出工具】</p>
 * <p>@author:【LIBO】</p>
 * <p>@date:【2018/8/27】</p>
 **/
public class ExcelUtils {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    private static final String dateFormat="yyyy-MM-dd";

    private static final SimpleDateFormat simpleDateFormat=new SimpleDateFormat(dateFormat);

    /**
     * excel sheet填充数据
     * @param dataList
     * @param wb
     * @param headers
     * @param sheetName
     */
    public static void fillExcelSheetData(List<Map<Integer, Object>> dataList, Workbook wb, String[] headers, String sheetName){
        Sheet sheet = wb.createSheet(sheetName);

        //TODO：创建sheet的第一行数据-即excel的头部信息
        Row headerRow=sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            headerRow.createCell(i).setCellValue(headers[i]);
        }

        //TODO：从第二行开始塞入真正的数据列表
        int rowIndex=1;
        Row row;
        Object obj;
        for(Map<Integer, Object> rowMap:dataList){
            try {
                row=sheet.createRow(rowIndex++);
                for(int i=0;i<headers.length;i++){
                    obj=rowMap.get(i);
                    if (obj==null) {
                        row.createCell(i).setCellValue("");
                    }else if (obj instanceof Date) {
                        String tempDate=simpleDateFormat.format((Date)obj);
                        row.createCell(i).setCellValue((tempDate==null)?"":tempDate);
                    }else {
                        row.createCell(i).setCellValue(String.valueOf(obj));
                    }
                }
            } catch (Exception e) {
                System.out.println("excel sheet填充数据 发生异常： " + e.fillInStackTrace());
            }
        }
    }

    /**
     * 下载Excel
     * @param response
     * @param wb
     * @param fileName
     * @throws Exception
     */
//    public static void downloadExcel(HttpServletResponse response, Workbook wb, String fileName) throws Exception{
//        String filenameEncode = new String(fileName.getBytes("utf-8"),"iso-8859-1");
//        response.setHeader("Content-Disposition", "attachment;filename="+ filenameEncode);
//        response.setContentType("application/ynd.ms-excel;charset=UTF-8");
//        OutputStream out=response.getOutputStream();
//        wb.write(out);
//        out.flush();
//        out.close();
//    }

}
